home *** CD-ROM | disk | FTP | other *** search
Text File | 1994-06-03 | 2.6 KB | 124 lines | [TEXT/MPS ] |
- /*************************************************************************************
- *
- * Apply a Heap Sort Algorithm to an offscreen, scrambled GWorld
- *
- * HeapSort.cp - C Source
- *
- * Copyright © Apple Computer, Inc. 1988 - 1993
- * All rights reserved.
- *
- * This is the "meat" of the SortPicts program. This file supplies the
- * core functionality to SortPicts by overiding and supplementing
- * the WindowObj class.
- *
- *************************************************************************************/
- #include "GWorldObj.h"
-
- /*************************************************************/
- /* */
- /* The Actual Sort Algorithms */
- /* */
- /*************************************************************/
-
-
-
- void GWorldObj::HeapSort( void)
- {
-
- long loop;
- long size;
- long *tickPtr = (long *)0x16A;
- char mmuMode = true32b;
-
- UseGWorld();
-
- SetTitle( (const unsigned char*)"\pHeap Sorting");
-
- #ifdef DEMO
- // This offsets for drawing directly to the screen
- offscreenPtr -= (long) ((**(((CWindowPtr)me)->portPixMap)).bounds.top * pictRowBytes) +
- (**(((CWindowPtr)me)->portPixMap)).bounds.left;
- #endif
-
- HLock( (Handle)sortList);
- sortListPtr = *sortList;
- if( !sortListPtr)
- return;
-
- BuildHeap();
-
- SwapMMUMode( &mmuMode);
-
- size = N - 1;
- for( loop = N-1; loop; --loop)
- {
- if( YieldIfTime( &mmuMode))
- goto SortErrQuit;
-
- ExchangeSortItem( 0, loop);
-
- Heapify( --size, 0);
- }
-
-
- UnuseGWorld();
- SwapMMUMode( &mmuMode);
-
- SortErrQuit:
- HUnlock( (Handle)sortList);
- SetTitle( (const unsigned char*)"\pDone");
-
- doneSorting = true;
- finishedTime = TickCount();
- DrawObj();
- }
-
- void GWorldObj :: BuildHeap( void)
- {
- long loop;
-
- for( loop = (N>>1)+3; loop; --loop)
- Heapify( N-1, loop -1);
-
- }
-
- //
- // This code adjusts for a zerø based array
- // (Where as the original source from Sedgewick (good book)
- // was 1..N, not 0..N-1
- //
-
- #define Left(i) (((i+1) << 1) -2)
- #define Right(i) (((i+1) << 1) -1)
-
- //
- // Typically, I would have used
- // #define Left(i) ((i) << 1)
- // #define Right(i) (((i) << 1) + 1)
- // #endif
-
- void GWorldObj :: Heapify( long size, long index)
- {
- long left, right, largest;
-
- left = Left( index);
- right = Right( index);
-
- largest = index;
-
- if( left <= size)
- if( sortListPtr[left] > sortListPtr[index])
- largest = left;
-
- if( right <= size)
- if( sortListPtr[right] > sortListPtr[largest])
- largest = right;
-
- if( largest != index)
- {
- ExchangeSortItem(index, largest);
- Heapify( size, largest);
- }
- }
-
-